package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class UserController {
    @Autowired
    private HttpSession httpSession;
    @Autowired
    private UserService userService;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    //发送短信
    @PostMapping("/user/sendMsg")
    public ResultInfo sendMsg(@RequestBody Map<String ,String> map){
        //接收参数
        String phone = map.get("phone");

        //生成验证码
        String code = "123";
        log.info("生成的验证码是:{}",code);

        //将验证码保存到session中
       // httpSession.setAttribute("SMS_"+phone,code);

        //验证码存在五分钟
        redisTemplate.opsForValue().set("SMS_"+phone,code,5, TimeUnit.MINUTES);

        //发送验证码到手机
        //smsTemplate.sendSms(phone,code);

        return ResultInfo.success(null);
    }
    //登录注册
    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        //接收参数
        String phone = map.get("phone");
        String code = map.get("code");
        //校验code
//        String codeFromSession= (String) httpSession.getAttribute("SMS_"+phone);
//        if (!StringUtils.equals(code, codeFromSession)
//                || StringUtils.isEmpty(code)
//                || StringUtils.isEmpty(codeFromSession)) {
//            return ResultInfo.error("验证码错误");
//        }

        //校验验证码
        String codeFormRides = (String) redisTemplate.opsForValue().get("SMS_"+phone);
        if (!StringUtils.equals(code,codeFormRides)
        ||StringUtils.isEmpty(code)
         ||StringUtils.isEmpty(codeFormRides)){
            return  ResultInfo.error("验证码错误");

        }


        //从数据库查询
        User user =  userService.findByPhone(phone);
        if (user != null){

        }else {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);//激活
            userService.save(user);
        }
        //将user信息保存到session
        httpSession.setAttribute("SESSION_USER",user);

        return ResultInfo.success(user);

    }
}
